package zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;

public class Jianting {
    ZooKeeper zk = null;

    @Before
    public void init()throws IOException {
        zk = new ZooKeeper("192.168.88.200:2181,192.168.88.201:2181,192.168.88.202:2181", 2000, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected && event.getType() == Event.EventType.NodeDataChanged) {
                    System.out.println(event.getPath()); // 收到的事件所发生的节点路径
                    System.out.println(event.getType()); // 收到的事件的类型
                    System.out.println("发生变化");      // 收到事件后，我们的处理逻辑

                    try {
                        zk.getData("/lxq/a", true, null);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else if(event.getState() == Event.KeeperState.SyncConnected && event.getType() == Event.EventType.NodeChildrenChanged){

                    System.out.println("子节点变化了......");
                }
            }
        });
    }

    @Test
    public void testGetWatch() throws Exception {

        byte[] data = zk.getData("/lxq/a", true, null); // 监听节点数据变化/

//        List<String> children = zk.getChildren("/lxq/a", true); //监听节点的子节点变化事件

        System.out.println(new String(data, "UTF-8"));

        Thread.sleep(Long.MAX_VALUE);
    }
}











